package com.qs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qs.constant.RedisConstant;
import com.qs.exception.ServiceException;
import com.qs.pojo.entity.OrderCart;
import com.qs.mapper.OrderCartMapper;
import com.qs.response.ResponseEnum;
import com.qs.service.IAsyncService;
import com.qs.service.IOrderCartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表和购物车表的一个关联表 服务实现类
 * </p>
 *
 * @author author
 * @since 2023-12-09
 */
@Service
@RequiredArgsConstructor
public class OrderCartServiceImpl extends ServiceImpl<OrderCartMapper, OrderCart> implements IOrderCartService {

    private final RedisTemplate redisTemplate;

    private final IAsyncService asyncService;

    @Override
    public List<Integer> getCartId(String orderId, Integer userId) {
        String redisOrderId = (String) redisTemplate.opsForValue().get(RedisConstant.ORDER_ID + orderId);
        if(StringUtils.isEmpty(redisOrderId)){
            List<Integer> cartIds = this.getCartIds(orderId, userId);
            //将锁定的商品库存解锁
            if(!CollectionUtils.isEmpty(cartIds)){
                asyncService.deductionLockStock(cartIds,orderId);
            }
            asyncService.deleteOrderIdExpire(orderId);
            asyncService.deleteOrderCart(orderId,userId);
            throw new ServiceException(ResponseEnum.ORDER_ID_EXPIRE);
        }
        List<Integer> cartIds = this.getCartIds(orderId, userId);
        return cartIds;
    }

    /**
     *
     * @param orderId
     * @param userId
     * @return
     */
    private List<Integer> getCartIds(String orderId,Integer userId){
        QueryWrapper<OrderCart> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id",orderId);
        wrapper.eq("user_id",userId);
        List<OrderCart> orderCarts = baseMapper.selectList(wrapper);
        if(!CollectionUtils.isEmpty(orderCarts)){
            List<Integer> cartIds = orderCarts.stream().map(OrderCart::getCartId).collect(Collectors.toList());
            return cartIds;
        }
        return null;
    }
}
